<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\common\model\log;

use think\Model;
use app\common\common\Helper;

/**
 * Description of BaiyangApiLogs
 *
 * @author dxx
 */
class BaiyangApiLogs extends Model {

    protected $table = 'baiyang_api_Logs';
    private $_baseTable = 'baiyang_api_Logs';
    protected $connection = ['database' => 'jooj_log'];

    public function __construct($data = array()) {
        $date = date('Ymd', time());
        $this->table = $this->_baseTable . '_' . $date;

        parent::__construct($data);
    }

    private function _createTable() {
        $sql = 'CREATE TABLE ' . $this->table . ' LIKE ' . $this->_baseTable;
        return $this->execute($sql);
    }

    public function addLog($inPut, $outPut, $isSuccess = 0, $url = '') {

        $apiUserId = $apiUserInfo['id'];

        $data = [
            'url' => $url,
            'param' => json_encode($inPut),
            'result' => json_encode($outPut),
            'api_user_id' => '0',
            'log_time' => time(),
            'is_success' => $isSuccess,
            'response_time' => microtime(true) - Helper::$requestTime
        ];

        try {
            $this->save($data);
        } catch (\Exception $e) {
            if (strstr($e->getMessage(), 'Base table or view not found')) {
                if (FALSE !== $this->_createTable()) {
                    $this->save($data);
                } else {
                    
                }
            }
        }
    }

}
